package tzy.recyclerview;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Administrator on 2018/4/24.
 */

public class RecyclerView2 extends RecyclerView {
    private OnItemClickListener mOnItemClickListener;
    private SimpleOnItemTouchListener mOnItemTouchListener;

    public RecyclerView2(@NonNull Context context) {
        this(context, null);
    }

    public RecyclerView2(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public RecyclerView2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        final GestureDetectorCompat gestureDetectorCompat = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                View child = findChildViewUnder(e.getX(), e.getY());
                if (mOnItemClickListener == null || child == null)
                    return false;
                ViewHolder viewHolder = getChildViewHolder(child);
                if (viewHolder == null)
                    return false;
                return performItemClick(child, viewHolder.getAdapterPosition(), viewHolder.getItemId());
            }


        });
        mOnItemTouchListener = new SimpleOnItemTouchListener() {
            @Override
            public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                gestureDetectorCompat.onTouchEvent(e);
            }

            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                gestureDetectorCompat.onTouchEvent(e);
                return false;
            }
        };
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }
    public boolean performItemClick(View child, int position, long id) {
        if (mOnItemClickListener == null)
            return false;
        mOnItemClickListener.onItemClick(this, child, position, id);
        return true;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        addOnItemTouchListener(mOnItemTouchListener);
    }

    @Override
    protected void onDetachedFromWindow() {
        removeOnItemTouchListener(mOnItemTouchListener);
        super.onDetachedFromWindow();
    }

    public static abstract class OnItemClickListener {
        public abstract void onItemClick(RecyclerView parent, View view, int position, long id);
    }

}
